<template>
    <!-- 遮罩层 -->
    <Transition name="modal-fade">
        <div 
            v-if="visible" 
            class="modal-overlay" 
            @click="handleClose"
            role="dialog"
            aria-modal="true"
            :aria-labelledby="company ? 'modal-title' : undefined"
        >
            <!-- 弹窗内容 -->
            <Transition name="modal-slide">
                <div v-if="visible && currentCompany" class="modal-content" @click.stop>
                    <!-- 加载状态 -->
                    <div v-if="detailsLoading" class="modal-loading">
                        <div class="loading-spinner" aria-label="加载中"></div>
                        <p>正在获取企业详情...</p>
                    </div>
                    
                    <!-- 错误状态 -->
                    <div v-else-if="detailsError" class="modal-error">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="12" cy="12" r="10"></circle>
                            <line x1="12" y1="8" x2="12" y2="12"></line>
                            <line x1="12" y1="16" x2="12.01" y2="16"></line>
                        </svg>
                        <p>{{ detailsError }}</p>
                        <button @click="loadCompanyDetails(currentCompany.id)" class="retry-button">重试</button>
                    </div>
                    
                    <!-- 正常内容 -->
                    <template v-else>
                        <!-- 关闭按钮 -->
                        <button 
                            class="modal-close" 
                            @click="handleClose" 
                            aria-label="关闭企业详情弹窗"
                            type="button"
                        >
                            <svg 
                                width="24" 
                                height="24" 
                                viewBox="0 0 24 24" 
                                fill="none" 
                                stroke="currentColor"
                                stroke-width="2" 
                                stroke-linecap="round" 
                                stroke-linejoin="round"
                                aria-hidden="true"
                            >
                                <line x1="18" y1="6" x2="6" y2="18"></line>
                                <line x1="6" y1="6" x2="18" y2="18"></line>
                            </svg>
                        </button>

                        <!-- 企业头部信息 -->
                        <header class="modal-header">
                            <div class="modal-header__logo" role="img" :aria-label="`${currentCompany.name}企业标志`">
                                <!-- 加载中状态 -->
                                <div v-if="imageLoading && !imageError" class="modal-header__logo-loading" aria-live="polite" aria-busy="true">
                                    <div class="loading-spinner" aria-label="加载中"></div>
                                </div>
                                
                                <!-- 图片加载成功 -->
                                <img 
                                    v-show="!imageLoading && !imageError && isValidImageUrl(currentCompany.logo)" 
                                    :src="currentCompany.logo"
                                    :alt="`${currentCompany.name}企业标志`" 
                                    :class="{ 'lazy-loaded': imageLoaded }"
                                    @load="handleImageLoad"
                                    @error="handleImageError" 
                                />
                                
                                <!-- 图片加载失败或无效URL时显示占位符 -->
                                <div 
                                    v-if="imageError || !isValidImageUrl(currentCompany.logo)" 
                                    class="modal-header__logo-placeholder"
                                    :aria-label="`${currentCompany.name}首字母标识`"
                                >
                                    {{ getInitial(currentCompany.name) }}
                                </div>
                            </div>
                            <div class="modal-header__info">
                                <h2 id="modal-title" class="modal-header__name">{{ currentCompany.name }}</h2>
                            </div>
                        </header>

                        <!-- 企业详细信息 -->
                        <main class="modal-body">
                            <!-- 企业简介 -->
                            <section class="modal-section" aria-labelledby="section-intro">
                                <h3 id="section-intro" class="modal-section__title">企业简介</h3>
                                <p class="modal-section__text">{{ currentCompany.description }}</p>
                            </section>

                            <!-- 企业标签 -->
                            <section v-if="currentCompany.tags && currentCompany.tags.length" class="modal-section" aria-labelledby="section-tags">
                                <h3 id="section-tags" class="modal-section__title">业务领域</h3>
                                <ul class="modal-tags" role="list">
                                    <li v-for="tag in currentCompany.tags" :key="tag" class="modal-tag">{{ tag }}</li>
                                </ul>
                            </section>
                        </main>
                    </template>
                </div>
            </Transition>
        </div>
    </Transition>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, computed } from 'vue';
import { fetchCompanyDetails } from '../../api/company.js';

const props = defineProps({
    company: {
        type: Object,
        default: null
    },
    visible: {
        type: Boolean,
        default: false
    }
});

const emit = defineEmits(['close']);

const imageError = ref(false);
const imageLoading = ref(true);
const imageLoaded = ref(false);
const companyDetails = ref(null);
const detailsLoading = ref(false);
const detailsError = ref(null);

const handleClose = () => {
    emit('close');
};

// 获取公司详情
const loadCompanyDetails = async (companyId) => {
    if (!companyId) return;
    
    try {
        detailsLoading.value = true;
        detailsError.value = null;
        const details = await fetchCompanyDetails(companyId);
        companyDetails.value = details;
    } catch (error) {
        detailsError.value = error.message || '获取公司详情失败';
        console.error('获取公司详情失败:', error);
    } finally {
        detailsLoading.value = false;
    }
};

// 获取当前显示的公司数据（优先使用API获取的详情）
const currentCompany = computed(() => {
    return companyDetails.value || props.company;
});

const isValidImageUrl = (url) => {
    if (!url) return false;
    return url.startsWith('http://') || url.startsWith('https://') || url.startsWith('/');
};

const handleImageLoad = () => {
    imageLoading.value = false;
    imageLoaded.value = true;
};

const handleImageError = () => {
    imageLoading.value = false;
    imageError.value = true;
};

const getInitial = (name) => {
    return name ? name.charAt(0).toUpperCase() : '?';
};

// 存储打开弹窗前的焦点元素
let previousActiveElement = null;

// ESC键关闭功能
const handleEscKey = (event) => {
    if (event.key === 'Escape' && props.visible) {
        handleClose();
    }
};

// 焦点陷阱 - 保持焦点在弹窗内
const handleTabKey = (event) => {
    if (!props.visible) return;
    
    const focusableElements = document.querySelectorAll(
        '.modal-content button, .modal-content a[href], .modal-content [tabindex]:not([tabindex="-1"])'
    );
    
    if (focusableElements.length === 0) return;
    
    const firstElement = focusableElements[0];
    const lastElement = focusableElements[focusableElements.length - 1];
    
    if (event.key === 'Tab') {
        if (event.shiftKey && document.activeElement === firstElement) {
            event.preventDefault();
            lastElement.focus();
        } else if (!event.shiftKey && document.activeElement === lastElement) {
            event.preventDefault();
            firstElement.focus();
        }
    }
};

// 监听visible变化，管理body滚动、焦点和重置图片状态
watch(() => props.visible, (newValue) => {
    if (newValue) {
        // 保存当前焦点元素
        previousActiveElement = document.activeElement;
        
        document.body.style.overflow = 'hidden';
        // 重置图片加载状态
        imageError.value = false;
        imageLoading.value = true;
        imageLoaded.value = false;
        
        // 重置详情数据
        companyDetails.value = null;
        detailsError.value = null;
        
        // 获取公司详情
        if (props.company && props.company.id) {
            loadCompanyDetails(props.company.id);
        }
        
        // 将焦点移到关闭按钮
        setTimeout(() => {
            const closeButton = document.querySelector('.modal-close');
            if (closeButton) closeButton.focus();
        }, 100);
    } else {
        document.body.style.overflow = '';
        
        // 恢复之前的焦点
        if (previousActiveElement && previousActiveElement.focus) {
            previousActiveElement.focus();
        }
    }
});

onMounted(() => {
    document.addEventListener('keydown', handleEscKey);
    document.addEventListener('keydown', handleTabKey);
});

onUnmounted(() => {
    document.removeEventListener('keydown', handleEscKey);
    document.removeEventListener('keydown', handleTabKey);
    document.body.style.overflow = '';
});
</script>

<style scoped>
/* 加载状态 */
.modal-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: var(--spacing-4xl) var(--spacing-lg);
    color: #80deea;
    text-align: center;
}

.modal-loading p {
    margin-top: var(--spacing-md);
    font-size: var(--font-size-lg);
}

/* 错误状态 */
.modal-error {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: var(--spacing-4xl) var(--spacing-lg);
    color: #ef5350;
    text-align: center;
}

.modal-error p {
    margin: var(--spacing-md) 0;
    font-size: var(--font-size-lg);
}

.retry-button {
    margin-top: var(--spacing-md);
    padding: var(--spacing-sm) var(--spacing-lg);
    background: rgba(77, 208, 225, 0.2);
    color: #4dd0e1;
    border: 1px solid #4dd0e1;
    border-radius: var(--radius-md);
    cursor: pointer;
    font-size: var(--font-size-base);
    transition: all var(--transition-smooth);
}

.retry-button:hover {
    background: rgba(77, 208, 225, 0.3);
    box-shadow: 0 0 15px rgba(77, 208, 225, 0.5);
}

/* 加载动画 */
.loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid rgba(77, 208, 225, 0.2);
    border-radius: 50%;
    border-top: 4px solid #4dd0e1;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 遮罩层 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.85);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2000;
    padding: var(--spacing-lg);
    overflow-y: auto;
}

/* 弹窗内容 */
.modal-content {
    background: rgba(13, 31, 60, 0.95);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(77, 208, 225, 0.3);
    border-radius: var(--radius-lg);
    max-width: 800px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;
    box-shadow: 0 0 40px rgba(77, 208, 225, 0.3);
}

/* 关闭按钮 */
.modal-close {
    position: absolute;
    top: var(--spacing-lg);
    right: var(--spacing-lg);
    width: 40px;
    height: 40px;
    border: 1px solid rgba(77, 208, 225, 0.3);
    background: rgba(26, 41, 66, 0.8);
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #4dd0e1;
    transition: all var(--transition-smooth);
    z-index: 10;
}

.modal-close:hover {
    background: rgba(77, 208, 225, 0.2);
    border-color: #4dd0e1;
    box-shadow: 0 0 15px rgba(77, 208, 225, 0.5);
    transform: rotate(90deg);
}

/* 头部区域 */
.modal-header {
    display: flex;
    gap: var(--spacing-xl);
    padding: var(--spacing-3xl);
    border-bottom: 1px solid rgba(77, 208, 225, 0.2);
    align-items: center;
}

.modal-header__logo {
    width: 120px;
    height: 120px;
    flex-shrink: 0;
    border-radius: var(--radius-md);
    overflow: hidden;
    background: rgba(26, 41, 66, 0.8);
    border: 1px solid rgba(77, 208, 225, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}

.modal-header__logo img {
    width: 100%;
    height: 100%;
    object-fit: contain;
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
}

.modal-header__logo img.lazy-loaded {
    opacity: 1;
}

.modal-header__logo-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: var(--font-size-4xl);
    font-weight: var(--font-weight-bold);
    background: linear-gradient(135deg, rgba(77, 208, 225, 0.2) 0%, rgba(38, 198, 218, 0.2) 100%);
    color: #4dd0e1;
    text-shadow: 0 0 10px rgba(77, 208, 225, 0.5);
}

.modal-header__logo-loading {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(26, 41, 66, 0.8);
}

.loading-spinner {
    width: 32px;
    height: 32px;
    border: 3px solid rgba(77, 208, 225, 0.2);
    border-top-color: #4dd0e1;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

.modal-header__info {
    flex: 1;
}

.modal-header__name {
    font-size: var(--font-size-3xl);
    font-weight: var(--font-weight-semibold);
    color: #4dd0e1;
    margin: 0 0 var(--spacing-sm) 0;
    line-height: var(--line-height-tight);
    text-shadow: 0 0 10px rgba(77, 208, 225, 0.4);
}

.modal-header__industry {
    font-size: var(--font-size-lg);
    color: #80deea;
    font-weight: var(--font-weight-medium);
    margin: 0 0 var(--spacing-md) 0;
}

.modal-header__badge {
    display: inline-flex;
    align-items: center;
    gap: var(--spacing-xs);
    background: rgba(77, 208, 225, 0.2);
    color: #4dd0e1;
    border: 1px solid rgba(77, 208, 225, 0.3);
    padding: var(--spacing-xs) var(--spacing-md);
    border-radius: var(--radius-full);
    font-size: var(--font-size-sm);
    font-weight: var(--font-weight-semibold);
}

/* 主体内容 */
.modal-body {
    padding: var(--spacing-3xl);
}

.modal-section {
    margin-bottom: var(--spacing-2xl);
}

.modal-section:last-child {
    margin-bottom: 0;
}

.modal-section__title {
    font-size: var(--font-size-xl);
    font-weight: var(--font-weight-semibold);
    color: #4dd0e1;
    margin: 0 0 var(--spacing-md) 0;
    line-height: var(--line-height-tight);
    text-shadow: 0 0 8px rgba(77, 208, 225, 0.3);
}

.modal-section__text {
    font-size: var(--font-size-base);
    color: #b0bec5;
    line-height: var(--line-height-relaxed);
    margin: 0;
}

/* 信息网格 */
.modal-info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: var(--spacing-lg);
    margin: 0;
}

.modal-info-item {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-xs);
}

.modal-info-item__label {
    font-size: var(--font-size-sm);
    color: var(--neutral-gray);
    font-weight: var(--font-weight-medium);
    margin: 0;
}

.modal-info-item__value {
    font-size: var(--font-size-base);
    color: var(--neutral-dark);
    font-weight: var(--font-weight-medium);
    margin: 0;
}

/* 标签 */
.modal-tags {
    display: flex;
    flex-wrap: wrap;
    gap: var(--spacing-sm);
    list-style: none;
    margin: 0;
    padding: 0;
}

.modal-tag {
    display: inline-block;
    padding: var(--spacing-xs) var(--spacing-md);
    background: rgba(77, 208, 225, 0.2);
    color: #4dd0e1;
    border: 1px solid rgba(77, 208, 225, 0.3);
    border-radius: var(--radius-full);
    font-size: var(--font-size-sm);
    font-weight: var(--font-weight-medium);
}

/* 联系信息 */
.modal-contact {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-md);
    font-style: normal;
}

.modal-contact-item {
    display: flex;
    align-items: center;
    gap: var(--spacing-sm);
    font-size: var(--font-size-base);
    color: var(--neutral-gray);
}

.modal-contact-item svg {
    color: var(--primary-color);
    flex-shrink: 0;
}

.modal-contact-item a {
    color: var(--primary-color);
    text-decoration: none;
    transition: color var(--transition-smooth);
}

.modal-contact-item a:hover {
    color: var(--primary-dark);
    text-decoration: underline;
}

.modal-contact-item a:focus-visible {
    outline: 2px solid var(--primary-color);
    outline-offset: 2px;
    border-radius: var(--radius-sm);
}

/* 动画 */
.modal-fade-enter-active,
.modal-fade-leave-active {
    transition: opacity 0.3s ease;
}

.modal-fade-enter-from,
.modal-fade-leave-to {
    opacity: 0;
}

.modal-slide-enter-active,
.modal-slide-leave-active {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.modal-slide-enter-from {
    opacity: 0;
    transform: scale(0.9) translateY(-20px);
}

.modal-slide-leave-to {
    opacity: 0;
    transform: scale(0.95);
}

/* 响应式 */
@media (max-width: 768px) {
    .modal-overlay {
        padding: 0;
        align-items: flex-start;
    }

    .modal-content {
        max-height: 100vh;
        border-radius: 0;
    }

    .modal-header {
        flex-direction: column;
        text-align: center;
        padding: var(--spacing-2xl) var(--spacing-lg);
    }

    .modal-header__logo {
        width: 100px;
        height: 100px;
    }

    .modal-header__name {
        font-size: var(--font-size-2xl);
    }

    .modal-body {
        padding: var(--spacing-lg);
    }

    .modal-info-grid {
        grid-template-columns: 1fr;
        gap: var(--spacing-md);
    }

    .modal-close {
        top: var(--spacing-md);
        right: var(--spacing-md);
        width: 36px;
        height: 36px;
    }
}
</style>
